package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.NumberUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.CacheConstants;
import com.zzyl.dto.AlertNotifyDto;
import com.zzyl.dto.AlertRuleDto;
import com.zzyl.entity.AlertData;
import com.zzyl.entity.AlertRule;
import com.zzyl.mapper.AlertDataMapper;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.mapper.DeviceMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.AlertRuleService;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.StringUtils;
import com.zzyl.vo.AlertRuleVo;
import com.zzyl.vo.DeviceDataVo;
import com.zzyl.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author sjqn
 */
@Slf4j
@Service
public class AlertRuleServiceImpl implements AlertRuleService {

    @Autowired
    private AlertRuleMapper alertRuleMapper;
    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 新增报警规则
     *
     * @param alertRuleDto 报警规则请求模型
     */
    @Override
    public void createRule(AlertRuleDto alertRuleDto) {
        AlertRule alertRule = BeanUtil.toBean(alertRuleDto, AlertRule.class);
        alertRuleMapper.insert(alertRule);
    }

    /**
     * 分页条件查询
     *
     * @param pageNum       页码
     * @param pageSize      页面大小
     * @param alertRuleName 报警规则名称
     * @param productKey    产品key
     * @param functionName  功能名称
     * @return 分页结果
     */
    @Override
    public PageResponse<AlertRuleVo> getAlertRulePage(Integer pageNum, Integer pageSize, String alertRuleName, String productKey, String functionName) {
        PageHelper.startPage(pageNum, pageSize);
        Page<AlertRuleVo> page = alertRuleMapper.page(alertRuleName, productKey, functionName);
        //添加提示
        page.getResult().forEach(alertRuleVo -> {
            String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", alertRuleVo.getFunctionName(), alertRuleVo.getOperator(), alertRuleVo.getValue(), alertRuleVo.getDuration());
            alertRuleVo.setRules(alertReason);
        });

        return PageResponse.of(page, AlertRuleVo.class);
    }

    /**
     * 删除报警
     *
     * @param id 报警规则id
     */
    @Override
    public void deleteAlertRule(Long id) {
        alertRuleMapper.deleteByPrimaryKey(id);
    }

    /**
     * 修改报警
     *
     * @param id           报警规则id
     * @param alertRuleDto 报警规则更新请求模型
     */
    @Override
    public void updateAlertRule(Long id, AlertRuleDto alertRuleDto) {
        AlertRule alertRule = BeanUtil.toBean(alertRuleDto, AlertRule.class);
        alertRuleMapper.updateByPrimaryKeySelective(alertRule);
    }

    /**
     * 查询报警信息
     *
     * @param id 报警规则id
     * @return 报警信息
     */
    @Override
    public AlertRuleVo readAlertRule(Long id) {
        AlertRule alertRule = alertRuleMapper.selectByPrimaryKey(id);
        return BeanUtil.toBean(alertRule, AlertRuleVo.class);
    }

    /**
     * 启用或禁用
     *
     * @param id     报警id
     * @param status 报警规则状态
     */
    @Override
    public void enableOrDisable(Long id, Integer status) {
        alertRuleMapper.updateStatus(id, status);
    }

    /**
     * 校验设备上报数据，进行报警规则过滤处理
     *
     * @param deviceDataVo 设备上报数据
     */
    @Override
    public void alertFilter(DeviceDataVo deviceDataVo) {
        //1. 获取设备上报数据时间，如果上报发生在1分钟前，为历史数据，不再处理
        LocalDateTime alarmTime = deviceDataVo.getAlarmTime();
        long between = LocalDateTimeUtil.between(alarmTime, LocalDateTime.now(), ChronoUnit.SECONDS);
        if (between > 60) {
            return;
        }
        //2. 准备设备对应的报警规则(产品规则+自身规则),非空判断
        List<AlertRule> allAlertRules = alertRuleMapper.selectByFunctionId(deviceDataVo.getFunctionId(), "-1", deviceDataVo.getProductKey());
        List<AlertRule> deviceAlertRules = alertRuleMapper.selectByFunctionId(deviceDataVo.getFunctionId(), deviceDataVo.getIotId(), deviceDataVo.getProductKey());
        Collection<AlertRule> alertRules = CollUtil.addAll(allAlertRules, deviceAlertRules);
        if (CollUtil.isEmpty(alertRules)) {
            return;
        }
        //3. 遍历规则验证是否报警
        alertRules.forEach(alertRule -> deviceDateAlarmHandler(deviceDataVo, alertRule));
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Value("${zzyl.alert.deviceMaintainerRole}")
    private String deviceMaintainerRole;

    @Value("${zzyl.alert.managerRole}")
    private String managerRole;

    /**
     * 设备数据报警处理器
     *
     * @param deviceDataVo
     * @param alertRule
     */
    private void deviceDateAlarmHandler(DeviceDataVo deviceDataVo, AlertRule alertRule) {
        //1. 判断报警时间是否在生效时间内
        String[] effectivePeriod = alertRule.getAlertEffectivePeriod().split("~");
        LocalTime startTime = LocalTime.parse(effectivePeriod[0]);
        LocalTime endTime = LocalTime.parse(effectivePeriod[1]);
        LocalTime alarmTime = LocalDateTimeUtil.of(deviceDataVo.getAlarmTime()).toLocalTime();
        if (alarmTime.isBefore(startTime) || alarmTime.isAfter(endTime)) {
            return;
        }
        //2. 判断数据是否超阈值
        // 超阈值次数Redis key
        String iotId = deviceDataVo.getIotId();
        String aggCountKey = CacheConstants.ALERT_TRIGGER_COUNT_PREFIX + iotId + deviceDataVo.getFunctionId() + ":" + alertRule.getId();
        // x – 第一个值，y – 第二个值。x==y返回0，x<y返回小于0的数，x>y返回大于0的数
        int compareResult = NumberUtil.compare(Double.parseDouble(deviceDataVo.getDataValue()), alertRule.getValue());
        if ((ObjectUtil.equals(alertRule.getOperator(), ">=") && compareResult >= 0)
                || (ObjectUtil.equals(alertRule.getOperator(), "<") && compareResult < 0)) {
            log.debug("设备上报数据达到阈值.");
        } else {
            // 未达阈值,删除redis累积的次数,程序结束
            redisTemplate.delete(aggCountKey);
            return;
        }
        //3. 判断是否处于沉默周期
        // redis获取沉默周期值(自定义,只看有无)
        String silentCacheKey = CacheConstants.ALERT_SILENT_PREFIX + iotId + deviceDataVo.getFunctionId() + ":" + alertRule.getId();
        String silentData = redisTemplate.opsForValue().get(silentCacheKey);
        if (StringUtils.isNotEmpty(silentData)) {
            return; //处于沉默周期就不报警
        }
        //4. 判断持续周期, 是否达到报警次数
        // 查询超阈值次数
        String times = redisTemplate.opsForValue().get(aggCountKey);
        int triggerCount = StringUtils.isEmpty(times) ? 1 : Integer.parseInt(times) + 1;
        if (ObjectUtil.notEqual(triggerCount, alertRule.getDuration())) {
            //未达到次数,次数+1保存
            redisTemplate.opsForValue().set(aggCountKey, String.valueOf(triggerCount));
            return;
        }
        // 达到次数,需要报警, 删除超阈值次数, 添加沉默周期(值自定义,规定沉默时间)
        redisTemplate.delete(aggCountKey);
        redisTemplate.opsForValue().set(silentCacheKey, deviceDataVo.getDataValue(), alertRule.getDuration(), TimeUnit.MINUTES);
        //5. 校验通过,获取报警消息消费者, 新增报警数据
        List<Long> userIdList = new ArrayList<>();
        if (deviceDataVo.getPhysicalLocationType() == -1) { // 老人设备
            if (deviceDataVo.getLocationType() == 0) {
                // 随身设备,通过老人获取护理员id
                userIdList = deviceMapper.selectNursingIdsByIotIdWithElder(deviceDataVo.getIotId());
            } else if (deviceDataVo.getLocationType() == 1) {
                // 固定设备,通过床位获取护理员id
                userIdList = deviceMapper.selectNursingIdsByIotIdWithElder(deviceDataVo.getIotId());
            }
        } else { // 非老人设备,获取维修员id
            userIdList = userRoleMapper.selectByRoleName(deviceMaintainerRole);
        }
        //获取超级管理员id
        List<Long> manageIdList = userRoleMapper.selectByRoleName(managerRole);
        //合并id列表
        List<Long> list = CollUtil.addAllIfNotContains(userIdList, manageIdList);
        list = CollUtil.distinct(list);
        //新增报警数据
        List<AlertData> alertDataList = insertAlertData(deviceDataVo, alertRule, list);

        //发送报警信息至相关管理人员
        websocketNotify(alertRule, alertDataList.get(0), list);
    }

    @Autowired
    private WebSocketServer websocketServer;

    /**
     * 发送websocket通知
     *
     * @param alertRule
     * @param alertData
     * @param userIds
     */
    private void websocketNotify(AlertRule alertRule, AlertData alertData, List<Long> userIds) {
        AlertNotifyDto alertNotifyDto = BeanUtil.toBean(alertData, AlertNotifyDto.class);
        alertNotifyDto.setFunctionName(alertRule.getFunctionName());
        alertNotifyDto.setAlertDataType(alertData.getType());
        alertNotifyDto.setNotifyType(1);

        websocketServer.sendMessageToConsumer(alertNotifyDto, userIds);
    }

    @Autowired
    private AlertDataMapper alertDataMapper;

    /**
     * 新增报警数据
     *
     * @param deviceDataVo 设备上报数据
     * @param alertRule    报警规则
     * @param consumerIds  消费者id列表
     * @return 报警数据
     */
    private List<AlertData> insertAlertData(DeviceDataVo deviceDataVo, AlertRule alertRule, List<Long> consumerIds) {
        String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", alertRule.getFunctionName(), alertRule.getOperator(), alertRule.getValue(), alertRule.getDuration());
        AlertData alertData = BeanUtil.toBean(deviceDataVo, AlertData.class);
        alertData.setAlertRuleId(alertRule.getId());
        alertData.setAlertReason(alertReason);
        alertData.setType(alertRule.getAlertDataType());
        alertData.setStatus(0);

        List<AlertData> list = consumerIds.stream().map(id -> {
            AlertData dbAlertData = BeanUtil.toBean(alertData, AlertData.class);
            dbAlertData.setUserId(id);
            return dbAlertData;
        }).collect(Collectors.toList());
        alertDataMapper.batchInsert(list);

        return list;
    }

}
